from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from typing import Dict, Any
import sys
import os

# 添加当前目录到Python路径（支持Debug Console）
current_dir = os.path.dirname(os.path.abspath(__file__))
parent_dir = os.path.dirname(current_dir)
if parent_dir not in sys.path:
    sys.path.insert(0, parent_dir)

# 自动路由发现系统
from app.core.router_discovery import auto_discover_routers, get_discovery_status

# 创建FastAPI应用实例
app = FastAPI(
    title="设备管理系统 API",
    description="基于FastAPI的设备管理系统",
    version="1.0.0"
)

# CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

def setup_routers(app: FastAPI) -> Dict[str, Any]:
    """
    设置路由系统
    使用自动发现机制注册所有API路由
    """
    print("🚀 启动自动路由发现系统...")
    
    # 自动发现并注册所有API路由
    api_dir = os.path.join(os.path.dirname(__file__), "api", "v1")
    registered_routes = auto_discover_routers(app, api_dir, prefix="/api/v1")
    
    # 获取详细状态
    discovery_status = get_discovery_status()
    
    return {
        "registered_routes": registered_routes,
        "discovery_status": discovery_status
    }

# 设置路由
router_setup_result = setup_routers(app)

# 尝试创建数据库表
database_available = False
try:
    from app.database.base import engine, Base
    # 创建数据库表
    Base.metadata.create_all(bind=engine)
    database_available = True
    print("数据库连接成功")
except Exception as e:
    print(f"数据库连接失败: {e}")
    print("将在没有数据库的情况下启动API服务")

# 初始化定时任务调度器
scheduler_available = False
try:
    from app.core.scheduler import start_scheduler, stop_scheduler
    import atexit
    
    # 启动调度器
    start_scheduler()
    scheduler_available = True
    print("✅ 定时任务调度器启动成功")
    
    # 注册关闭处理
    atexit.register(stop_scheduler)
    
except Exception as e:
    print(f"❌ 定时任务调度器启动失败: {e}")
    print("将在没有调度器的情况下启动API服务")

# 获取路由注册结果
registered_routes = router_setup_result.get("registered_routes", [])
discovery_status = router_setup_result.get("discovery_status", {})

print(f"\n=== 自动路由发现结果 ===")
if registered_routes:
    print(f"✅ 成功注册的API路由: {', '.join(registered_routes)}")
    print(f"✅ 总路由数量: {len(app.routes)}")
    
    # 显示详细统计
    summary = discovery_status.get("summary", {})
    print(f"📊 扫描统计: 总计 {summary.get('total_scanned', 0)} 个模块")
    print(f"   - 成功注册: {summary.get('successful', 0)} 个")
    print(f"   - 跳过模块: {summary.get('skipped', 0)} 个")
    print(f"   - 注册失败: {summary.get('failed', 0)} 个")
else:
    print("❌ 警告: 没有成功注册任何API路由")

@app.get("/")
async def root():
    return {
        "message": "设备管理系统 API",
        "database_status": "connected" if database_available else "disconnected",
        "scheduler_status": "running" if scheduler_available else "stopped",
        "registered_routes": registered_routes,
        "discovery_status": discovery_status,
        "docs_url": "/docs",
        "redoc_url": "/redoc",
        "api_base_url": "/api/v1",
        "features": {
            "auto_router_discovery": True,
            "scheduled_jobs": scheduler_available,
            "device_management": True,
            "maintenance_management": True,
            "user_authentication": True
        }
    }

@app.get("/health")
async def health_check():
    return {"status": "healthy"}

@app.get("/routers/status")
async def get_router_status():
    """获取路由注册状态"""
    return get_discovery_status()

@app.get("/routers/summary")
async def get_router_summary():
    """获取路由注册摘要"""
    status = get_discovery_status()
    return {
        "total_routes": len(app.routes),
        "api_routes": len(registered_routes),
        "discovery_summary": status.get("summary", {}),
        "registered_modules": status.get("registered", []),
        "auto_discovery_enabled": True
    }

def start_server(disable_bytecode: bool = True):
    """
    启动服务器的函数，支持Debug Console调用
    
    Args:
        disable_bytecode: 是否禁用Python字节码生成（禁止__pycache__文件夹）
    """
    import uvicorn
    import os
    
    # 设置环境变量禁用字节码生成
    if disable_bytecode:
        os.environ['PYTHONDONTWRITEBYTECODE'] = '1'
        print("🚫 已禁用Python字节码生成（不会生成__pycache__文件夹）")
    
    port = 8088
    print("正在启动FastAPI服务器...")
    print(f"API文档地址: http://localhost:{port}/docs")
    print(f"Redoc文档地址: http://localhost:{port}/redoc")
    print(f"服务状态: http://localhost:{port}/")
    uvicorn.run(app, host="0.0.0.0", port=port)

if __name__ == "__main__":
    start_server()
else:
    # 在Debug Console中可以调用 start_server() 来启动服务
    print("模块已加载，在Debug Console中执行: start_server() 来启动服务")
    print(f"或者访问: http://localhost:8088/docs 查看API文档")